import { Controller, Post, UploadedFile, UseInterceptors, Body, UseGuards, InternalServerErrorException } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { FileInterceptor } from '@nestjs/platform-express';
import { ApiBody, ApiConsumes, ApiProperty, ApiQuery, ApiTags } from '@nestjs/swagger';
import { Express } from 'express'
import * as crypto from 'crypto'
import * as fs from 'fs'
import * as path from 'path'
class FileUploadDto {
    @ApiProperty({ type: 'string', format: 'binary' })
    file: any;
}

@Controller()
@ApiTags('AppModule')
export class AppController {

    // 根据buffer返回一个文件名
    md5FileSync(buffer: Buffer) {
        const hash = crypto.createHash('md5')
        hash.update(buffer)
        return hash.digest('hex')
    }

    /**
     * 前端文件上传
     */
    @UseGuards(AuthGuard('jwt'))
    @Post('fileUpload')
    @UseInterceptors(FileInterceptor('file'))
    @ApiConsumes('multipart/form-data')
    @ApiBody({
        description: '文件列表',
        type: FileUploadDto,
    })
    uploadFile(@UploadedFile() file: Express.Multer.File, @Body() body: any) {
        const hashMap = this.md5FileSync(file.buffer)
        if (file.size > 10 * 1024 * 1024) {
            throw new InternalServerErrorException({
                errMsg: '文件上传不能超过10m'
            })
        }
        const newFileName = hashMap + path.extname(file.originalname)
        try {
            // 把buffer写到文件里
            fs.writeFileSync(path.resolve(process.env.STATIC_FILES_PATH, newFileName), file.buffer)
        } catch (error) {
            throw new InternalServerErrorException({
                errMsg: '文件写入失败'
            })
        }
        return { filename: newFileName }
    }

}

